<template>
    <n-card :bordered="false" size="small" style="border-top: 1px solid #eeeeee;padding-bottom: 1vh">
        <template #header>
            <div style="display:flex; gap: 0.5vw; align-items: baseline;">
                <router-link :to="{name: 'Detail', params: {id: answer.questionId}}">
                    <h3 v-html="titleHighlight"></h3>
                </router-link>
                <n-tag v-if="answer.isTop" :bordered="false"
                       style="float:right; font-weight: 600; border-radius: 0.3vw; margin-right: 1vw;"
                       type="error">
                    置顶
                </n-tag>
                <n-tag v-if="answer.isEssential" :bordered="false" style="font-weight: 600; border-radius: 0.3vw"
                       type="info">
                    精华
                </n-tag>
            </div>
        </template>
        <n-thing v-if="answer.content" style="flex-direction: column">
            <template #avatar>
                <n-avatar
                    :size="40"
                    :style="{color: 'white', backgroundColor: 'orange', fontSize: '20px'}"
                >{{ answer.username.toString().substring(0, 1) }}
                </n-avatar>
            </template>
            <template #header>
                <span style="font-size: 16px; font-weight: bold;">{{ answer.username }}</span>
            </template>
            <template #description>
                <n-text style="color:#646464;">{{ answer.introduction || '这个人很神秘，什么都没有写' }}</n-text>
            </template>
            <n-ellipsis :line-clamp="2" :tooltip="false" expand-trigger="click">
                <div v-highlight style="font-size: 14px;" v-html="contentHighlight"></div>
            </n-ellipsis>
            <template #footer>
                <n-text depth="3">发布于{{ $dayjs(answer.createTime).format('YYYY-MM-DD HH:mm') }}</n-text>
            </template>
            <template #action>
                <n-space align="center" size="large">
                    <n-button :disabled="true" secondary strong type="primary">
                        <template #icon>
                            <n-icon color="#18a058">
                                <CaretUp></CaretUp>
                            </n-icon>
                        </template>
                        <n-text type="success">赞同 {{ answer.voteCount || '' }}</n-text>
                    </n-button>
                    <n-button :quaternary="true" type="tertiary" @click="handleComment">
                        <template #icon>
                            <n-icon>
                                <Comments></Comments>
                            </n-icon>
                        </template>
                        <n-text v-if="commentCount" depth="3">{{ commentCount }} 条评论</n-text>
                        <n-text v-else depth="3">添加评论</n-text>
                    </n-button>
                    <n-button v-if="userState" :quaternary="true" type="info" @click="handleEditAnswer">
                        <template #icon>
                            <n-icon>
                                <EditRegular></EditRegular>
                            </n-icon>
                        </template>
                        修改
                    </n-button>
                    <n-button v-if="userState&&!isCollection" :quaternary="true" type="error"
                              @click="handleRemoveAnswer">
                        <template #icon>
                            <n-icon>
                                <TrashAltRegular/>
                            </n-icon>
                        </template>
                        删除
                    </n-button>
                </n-space>
            </template>
        </n-thing>
        <n-thing v-else depth="3">
            <template #description>
                <n-ellipsis :line-clamp="2" :tooltip="false" v-html="contentHighlight"></n-ellipsis>
            </template>
            <template #footer>
                <n-text :strong="true" depth="3">{{ $dayjs(answer.questionCreateTime).format('YYYY-MM-DD HH:mm') }} ·
                    {{ answer.answerCount }} 个回答
                </n-text>
            </template>
        </n-thing>
        <n-card v-if="showCommentInput" :bordered="false" :embedded="true" size="small" style="margin-top: 1vh;">
            <n-input
                v-model:value="comment.content"
                :autosize="true"
                placeholder="询问细节或提出修改意见"
                type="textarea"
            />
            <template #footer>
                <n-text depth="3">如果对你有帮助，记得点赞支持</n-text>
                <n-button style="float:right;" type="primary" @click="handleSubmitComment">提交评论</n-button>
            </template>
        </n-card>
        <n-modal
            v-model:show="showModal"
            :bordered="false"
            :style="bodyStyle"
            :title="answer.title"
            class="custom-card"
            preset="card"
        >
            <div id="vditor"></div>
            <template #footer>
                <n-space justify="space-between">
                    <n-button @click="showDrawer = true">补充细节</n-button>
                    <n-button type="primary" @click="handleSubmitAnswer">提交修改</n-button>
                </n-space>
            </template>
        </n-modal>
        <n-drawer v-model:show="showDrawer" :width="500">
            <n-drawer-content closable title="亿点点细节">
                <n-scrollbar>
                    <n-form ref="moreInfoFormRef" :model="answerDTO" size="large">
                        <n-form-item label="修改后的代码">
                            <n-input
                                v-model:value="answerDTO.modifiedCode"
                                :autosize="{ minRows: 3 }"
                                type="textarea"
                            />
                        </n-form-item>
                        <n-form-item label="错误类型">
                            <n-input v-model:value="answerDTO.errorType" :autosize="{ minRows: 1 }" type="textarea"/>
                        </n-form-item>
                        <n-form-item label="错误分析">
                            <n-input
                                v-model:value="answerDTO.errorDesc"
                                type="text"
                            />
                        </n-form-item>
                        <n-form-item label="出错代码">
                            <n-input
                                v-model:value="answerDTO.errorDesc"
                                :autosize="{ minRows: 3 }"
                                type="textarea"
                            />
                        </n-form-item>
                        <n-form-item label="出错的行">
                            <n-input
                                v-model:value="answerDTO.errorRow"
                                type="text"
                            />
                        </n-form-item>
                        <n-form-item label="出错的列">
                            <n-input
                                v-model:value="answerDTO.errorColumn"
                                type="text"
                            />
                        </n-form-item>
                        <n-form-item label="变化前的代码">
                            <n-input
                                v-model:value="answerDTO.codeBeforeChange"
                                :autosize="{ minRows: 3 }"
                                type="textarea"
                            />
                        </n-form-item>
                        <n-form-item label="变化后的代码">
                            <n-input
                                v-model:value="answerDTO.codeAfterChange"
                                :autosize="{ minRows: 3 }"
                                type="textarea"
                            />
                        </n-form-item>
                    </n-form>
                </n-scrollbar>
            </n-drawer-content>
        </n-drawer>
    </n-card>
</template>

<script setup>
import { CaretUp, Comments, EditRegular, TrashAltRegular } from '@vicons/fa'
import { computed, nextTick, onMounted, ref } from 'vue'
import Vditor from 'vditor'
import 'vditor/dist/index.css'
import { removeAnswer, updateAnswer } from '../api/answer'
import { useDialog, useMessage } from 'naive-ui'
import { marked } from 'marked'
import { insertComment, listComments } from '../api/comment'
import { useRoute } from 'vue-router'
import { useUserStore } from '../store/user'
import { highlightKeyword } from '../utils/mini-lodash'

const props = defineProps({
    answer: {
        id: Number,
        questionId: Number,
        title: String,
        content: String,
        username: String,
        introduction: String,
        voteCount: Number,
        createTime: Date,
        questionContent: String,
        questionCreateTime: Date,
        questionUpdateTime: Date,
        answerCount: Number,
        isTop: Boolean,
        isEssential: Boolean,
    },
    userState: Boolean,
    isCollection: Boolean,
})
const dialog = useDialog()
const message = useMessage()
const showModal = ref(false)
const bodyStyle = {
    width: '600px',
}
const showDrawer = ref(false)
const vditor = ref(null)
const handleEditAnswer = () => {
    showModal.value = true
    nextTick(() => {
            vditor.value = new Vditor('vditor', {
                after: () => {
                    vditor.value.setValue(props.answer.content, true)
                },
                height: 500,
                width: '100%',
                icon: 'material',
                mode: 'wysiwyg',
                tab: '    ',
                placeholder: '内容描述',
                typewriterMode: true,
                undoDelay: 1500,
                hint: {
                    emojiTail: '设置常用表情',
                },
                counter: {
                    enable: true,
                },
                preview: {
                    hljs: {
                        lineNumber: true,
                        style: 'native',
                    },
                },
                toolbar: [
                    'emoji', 'headings', 'bold', 'italic',
                    'strike', 'link', 'ordered-list', 'check', '|',
                    'quote', 'line', 'code', 'inline-code', 'fullscreen',
                    'edit-mode', '|', 'undo', 'redo', 'code-theme',
                    'content-theme', 'preview', 'help', 'outline',
                ],
            })
        },
    )
}
const handleRemoveAnswer = () => {
    dialog.warning({
        title: '注意',
        content: '你确定要删除自己的答案吗？',
        positiveText: '确定',
        negativeText: '不确定',
        onPositiveClick: () => {
            removeAnswer(props.answer.id).then(res => {
                if (res.code === '204') {
                    message.success('删除成功！')
                    window.location.reload()
                }
            })
        },
    })
}
const answerDTO = ref({
    content: '',
    modifiedCode: '',
    errorCode: '',
    errorType: '',
    errorDesc: '',
    errorColumn: '',
    errorRow: '',
    codeBeforeChange: '',
    codeAfterChange: '',
})
const handleSubmitAnswer = () => {
    answerDTO.value.content = vditor.value.getValue()
    updateAnswer(props.answer.id, answerDTO.value).then(res => {
        if (res.code === '200') {
            props.answer.content = res.data.content
            showModal.value = false
            message.success('修改成功！')
        }
    })
}

const route = useRoute()
const userStore = useUserStore()
const commentCount = ref(0)
const comments = ref([])
const showCommentInput = ref(false)
const comment = ref({
    content: '',
    questionId: route.params.id,
    answerId: props.answer.id,
    rootCommentId: null,
    replyTo: null,
    createTime: null,
})
const handleComment = () => {
    showCommentInput.value = !showCommentInput.value
}
const handleSubmitComment = () => {
    if (userStore.token === '') {
        message.warning('你还没登录，请登录后再试！')
    } else if (comment.value.content === '') {
        message.warning('你还没有写评论！')
    } else {
        insertComment(comment.value, props.answer.id).then(res => {
            if (res.code === '201') {
                message.success('评论成功！')
                comment.value.content = ''
                updateCommentList(props.answer.id)
            } else {
                message.error('出错啦！')
            }
        })
    }
}
const updateCommentList = async (answerId) => {
    await listComments(answerId).then(res => {
        comments.value = res.data
    })
}
onMounted(() => {
        if (props.answer.id !== null) {
            listComments(props.answer.id).then(res => {
                if (res.code === '200') {
                    commentCount.value = res.data.length
                    comments.value = res.data
                }
            })
            answerDTO.value = { ...props.answer }
        }
    },
)

const titleHighlight = computed(() => {
        return highlightKeyword(props.answer.title, route.params.keyword)
    },
)
const contentHighlight = computed(() => {
        if (route.name === 'User') {
            return marked.parse(props.answer.content)
        } else {
            let temp = highlightKeyword(props.answer.content, route.params.keyword)
            return marked.parse(temp)
        }
    },
)
</script>

<style scoped>
h3:hover {
    color: #18a058;
}

.n-thing:deep(.n-thing-avatar-header-wrapper) {
    display: flex;
    flex-wrap: nowrap;
    align-items: center;
}

.n-thing:deep(.n-thing-main .n-thing-header) {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 0;
}

.n-card:deep(.n-card-header) {
    padding-bottom: 0;
}
</style>
